class code4 {
    //全排列 II
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permuteUnique(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];
        //先排序
        Arrays.sort(nums);
        dfs(nums,0);
        return ret;
    }

    public void dfs(int[] nums,int pos) {
        //出口
        if(nums.length == path.size()) {
            ret.add(new ArrayList<>(path));
            return;
        }

        for(int i=0;i<nums.length;i++) {
            //剪枝(当前的数重复使用||同一个数只能用一次)
            if(check[i]==true||(i!=0 &&nums[i]==nums[i-1]&&check[i-1]==false)) {
                continue;
            }
            path.add(nums[i]);
            check[i] = true;
            dfs(nums,pos+1);
            //回溯
            check[i] = false;
            path.remove(path.size()-1);
        }
    }
}
